#pragma once
#include "Buffer.hpp"
#include <map>
#include <functional>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
using namespace std;
// 定义状态码枚举
enum class StatusCode
{
    Unknown,
    ok = 200,
    MovePermanently = 301,
    MoveTemporarily = 302,
    BadRequest = 400,
    NotFound = 404
};
// 定义结构体
class HttpResponse
{
public:
    HttpResponse()
    {
        m_statusCode = StatusCode::Unknown;
        m_headers.clear();
        m_filename = string();
        m_sendDataFunc = nullptr;
    }
    ~HttpResponse(){}

    // 添加响应头
    void addHeader(const string key,const string value)
    {
        if(key.empty() || value.empty())
        {
            return ;
        }
        m_headers.insert(make_pair(key,value));
    }

    // 组织http响应数据
    void prepareMsg(Buffer *sendBuf, int socket)
    {
        // 状态行
        char tmp[1024] = {0};
        int code = static_cast<int>(m_statusCode);
        sprintf(tmp, "HTTP/1.1 %d %s\r\n", code, m_info.at(code).data());
        sendBuf->appendString(tmp);
        // 响应头
        for (auto it = m_headers.begin();it!=m_headers.end();++it)
        {
            sprintf(tmp, "%s: %s\r\n", it->first.data(),it->second.data());
            sendBuf->appendString(tmp);
        }
        // 空行
            sendBuf->appendString("\r\n");
    #ifndef MSG_SEND_AUTO // 如果没有定义这个宏，下面代码有效，否则无效
        sendBuf->sendData(socket);
    #endif
        // 回复的数据
       m_sendDataFunc(m_filename, sendBuf, socket);
    }
    
    function<void(const string, Buffer *, int)> m_sendDataFunc;
    inline void setFileName(string name)
    {
        m_filename = name;
    }
    inline void setStatusCode(StatusCode code)
    {
        m_statusCode = code;
    }
private:
    // 状态行:状态码（整型数），状态描述（字符串）
    StatusCode m_statusCode;
    string m_filename;
    map<string, string> m_headers;
    // 定义状态码和描述对应关系
    const map<int, string> m_info = {
        {200, "ok"},
        {301, "MovePermanently"},
        {302, "MoveTemporarily"},
        {400, "BadRequest"},
        {404, "NotFound"},
    };
};
